using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Xml.Serialization;
using Microsoft.SharePoint.WebControls;

namespace OrbitOne.SharePoint.Provision.WebParts
{
    [Guid("cd3f2772-d3ce-495e-880f-db030774250a"),
     ToolboxData("<{0}:ChangePasswordWebPart runat=server></{0}:ChangePasswordWebPart>"),
    XmlRoot(Namespace = "OrbitOne.Provision.WebParts")]
    public class ChangePasswordWebPart :GeneralWebPart
    {
        // Declare variables for HtmlControls user interface elements.
        HtmlInputPassword _oldPassword;
        HtmlInputPassword _newPassword;
        HtmlInputPassword _newPasswordVerify;
        HtmlTextArea _status;
        HtmlButton _goButton;
        

        
        


        protected override void OnLoad(EventArgs e)
        {
            // Get the URL of the current site
            _siteUrl = SPControl.GetContextWeb(Context).Url.ToString();

            // Determine which type of provider is being used: AD or SQL (either are supported)
            DetermineProviderType();
           
            base.OnLoad(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            // If this web part is being drawn and no failure has occured,
            //  the make sure textbox values are cleared
            if (!_failure)
            {
                // Clear the fields
                _oldPassword.Value = "";
                _newPassword.Value = "";
                _newPasswordVerify.Value = "";
            }
            _newPasswordVerify.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + _goButton.ClientID + "').click();return false;}} else {return true}; ");
            base.OnPreRender(e);
           
        }

        protected override void CreateChildControls()
        {
            _oldPassword = new HtmlInputPassword();
            _newPassword = new HtmlInputPassword();
            _newPasswordVerify = new HtmlInputPassword();
            _goButton = new HtmlButton();
            _status = new HtmlTextArea();
           
            // Button text
            _goButton.InnerText = "Change Password";

            // Add an event handler when the button is clicked
            _goButton.ServerClick += new EventHandler(_goButton_ServerClick);

            // Add the controls to the web part
            Controls.Add(_oldPassword);
            Controls.Add(_newPassword);
            Controls.Add(_newPasswordVerify);
            Controls.Add(_goButton);
            Controls.Add(_status);
        }


        // User clicks on the button to change the password
        public void _goButton_ServerClick(object sender, EventArgs e)
        {
            string userName;

            try
            {
                // WRITE YOUR CODE TO ENFORCE YOUR PASSWORD POLICY IN THIS METHOD:
                CheckPassword(_newPassword.Value.ToString(), _newPasswordVerify.Value.ToString());

                // Get the current username
                userName = Context.User.Identity.Name;
                userName = Helper.GetUserNameFromIdentity((userName));
                if (_providerType == "WindowsIntergrated")
                {
                    
                    using (ElevationManager evelate = new ElevationManager())
                    {
                        string connectionString = SiteCollectionLADPConnectionString;
                        if (ADProvisioning.ValidateOldPassword(userName, _oldPassword.Value, connectionString))

                            ADProvisioning.ResetPassword(userName, _newPassword.Value.ToString(), connectionString);
                        else
                            throw new Exception("The old password is incorrect.  Your password could not be changed.");
                    }
                    _status.Value = "Your password has been successfully changed.";
                    _failure = false;
                }

                    // Make sure the old password is correct
                else if (Membership.ValidateUser(userName, _oldPassword.Value.ToString()))
                {

                    if (_providerType == "SQL")
                    {
                        // Get the provider name

                        // Change the user's password
                        SQLProvisioning.ChangePassword(userName, _oldPassword.Value.ToString(), _newPassword.Value.ToString());
                    }
                    else if (_providerType == "AD")
                    {
                        // Impersonate the user specified in the web.config file who has permissions to complete these tasks
                        using (ElevationManager evelate = new ElevationManager())
                        {
                            // Set the new password for the user
                            ADProvisioning.ResetPassword(Context.User.Identity.Name, _newPassword.Value.ToString(),ADRootLADPConnectionString);
                        }
                    }
                    else
                    {
                        // Unknown provider type - return an error message
                        throw new Exception("Your password could not be changed.  The authentication provider for this site could not be found.  Please contact your administrator for assistance.");
                    }

                    _status.Value = "Your password has been successfully changed.";
                    _failure = false;
                }
                else // old password not verified
                {
                    throw new Exception("The old password is incorrect.  Your password could not be changed.");
                }

            }
            catch (Exception ex)
            {
                _status.Value = ex.Message;
                _failure = true;
            }
        }
       
        /// <summary>
        /// Build the Web Part user interface
        /// </summary>
        /// <param name="output">The HtmlTextWriter to render the output</param>
        private void BuildWSSUI(HtmlTextWriter output)
        {
            string messageColor;

            // Write any error or status messages
            if (_failure)
            {
                messageColor = "Red";
            }
            else
            {
                messageColor = "Green";
            }

            BuildStatus(_status.Value.ToString(), messageColor, output);

            // Start the table
            output.Write("<TABLE border='0' width='100%' cellspacing='0' cellpadding='0'>");

            // Build a row for each control
            BuildRow("Old Password", "Enter your old password.", _oldPassword, output);
            LineBreak("OldPassword", output);
            BuildRow("New Password", "Enter a new password.", _newPassword, output);
            LineBreak("NewPassword", output);
            BuildRow("Confirm New Password", "Retype the new password and make sure it matches the previous field.", _newPasswordVerify, output);
            LineBreak("EndVerifyPassword", output);

            // Draw the buttons
            BuildButton(_goButton, output);
            LineBreak("EndGoButton", output, 2);

            // End the table
            output.Write("</TABLE>");

        }
        public override void RenderControl(HtmlTextWriter writer)
        {
            // Build the full user interface
            BuildWSSUI(writer);
        }
    }
}
